package com.qdxwx.web.controller.order;

import com.alibaba.fastjson2.JSONObject;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.coupon.CouponService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.data.service.member.MemberSaleService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.order.OrderDetailService;
import com.qdxwx.data.service.order.OrderExpressService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.data.service.shopcart.ShopCartService;
import com.qdxwx.data.service.user.*;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.book.Book;
import com.qdxwx.models.company.Company;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.coupon.CouponCodeDTO;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.course.CourseDTO;
import com.qdxwx.models.document.Document;
import com.qdxwx.models.enums.*;
import com.qdxwx.models.member.MemberSale;
import com.qdxwx.models.member.MemberType;
import com.qdxwx.models.order.Order;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.order.OrderDetailQuery;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.models.shopcart.ShopCart;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserThird;
import com.qdxwx.payment.alipay.AliPay;
import com.qdxwx.payment.wxpay.WxPay;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Order接口
 * @author developer
 */
@Controller
@RequestMapping("/order")
public class OrderCreateController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(OrderCreateController.class);

	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private MemberTypeService memberTypeService;
	@Autowired
	private ShopCartService shopCartService;
	@Autowired
	private MemberSaleService memberSaleService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private BookService bookService;
	@Autowired
	private PictureService pictureService;
	@Autowired
	private DocumentService documentService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private CouponCodeService couponCodeService;
	@Autowired
	private UserThirdService userThirdService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private UserInviteService userInviteService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderExpressService orderExpressService;
	@Autowired
	private UserLetterService userLetterService;
	@Autowired
	private UserBuyService userBuyService;

	/**
	 * 创建购物车订单
	 */
	@RequestMapping(value = "/create.json")
	@ResponseBody
	public AjaxResult createOrder(HttpServletRequest request) {
		User user = LoginUser.getUser(request);
		if (user == null) {
			return AjaxResult.error("您未登录，请登录再进行操作！");
		}
		OrderType orderType = OrderType.get(request.getParameter("orderType"));//订单商品类型
		if (orderType == null) {
			return AjaxResult.error("订单类型错误！");
		}
		if (OrderType.COURSE == orderType) {
			//return createCourseOrders(request, user); //购物车创建订单
			return createCourseOrder(request, user);
		} else if (OrderType.MEMBER == orderType) {
			return createMemberOrder(request, user);
		} else if (OrderType.ACCOUNT == orderType) {
			return createAccountOrder(request, user);
		}else if(OrderType.BOOK == orderType){
			return createBookOrder(request, user);
		}else if(OrderType.PICTURE == orderType){
			return createPictureOrder(request, user);
		}else if(OrderType.DOCUMENT == orderType){
			return createDocumentOrder(request, user);
		} else {
			return AjaxResult.error("OrderType参数错误！");
		}
	}

	/**
	 * 跳过购物车购买课程订单
	 * @param request
	 * @return
	 */
	public AjaxResult createCourseOrder(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		int otherId = TKConvert.toInteger(request.getParameter("otherId"));
		LocalDateTime curTime = LocalDateTime.now();
		Course course = courseService.get(otherId);
		if (ObjectUtils.isNull(course)) {
			return AjaxResult.error("找不到该课程！");
		}
		boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.COURSE.ordinal(), otherId);
		if (isBuy) {
			return AjaxResult.error("您已经报名了此课程，不需要重复报名，请手动刷新页面后进入观看！");
		}
		//原始金额
		int orderAmount = course.getPrice();
		if (orderAmount <= 0) {
			return AjaxResult.error("需要支付的金额错误，请刷新页面后重试！");
		}
		// 拼装订单数据
		Order order = orderService.getRepeatOrder(user.getUserId(), otherId, OrderType.COURSE.toString());
		if (order == null) {
			order = new Order();
			order.setImgUrl(course.getCover());
			order.setCreateTime(curTime);// 下单时间
			// 下单时间
			order.setCompanyId(company.getCompanyId()); //这里是平台机构Id，不是用户机构Id
			order.setUserId(user.getUserId());
			order.setUserName(user.getDisplayName());
			order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
			order.setStatus(OrderStatus.INIT.toString());// 交易装态
			order.setPayType(payType.toString());// 支付类型
			order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
			order.setReqIp(TKRequest.getIpAddr(request));
			order.setOrderType(OrderType.COURSE.toString());//商品类型
			order.setDescription("购买课程：" + course.getCourseName());
			order.setOrderAmount(orderAmount); // 原始金额
			order.setCouponAmount(0);
			order.setPayAmount(orderAmount);//订单实际支付金额
			order.setCashAmount(orderAmount);//在线支付金额
			order.setVmAmount(0);//虚拟账户扣除金额
			order.setBackAmount(0);//返现扣除金额
			// 添加订单
			int count = orderService.insert(order);
			if (count < 1) {
				return AjaxResult.error("创建订单失败！");
			}
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setUserId(user.getUserId());
			orderDetail.setUserName(user.getDisplayName());
			orderDetail.setOrderId(order.getOrderId());
			orderDetail.setAuthDate(course.getExpireDate());
			orderDetail.setCreateTime(curTime);
			orderDetail.setSourcePrice(course.getSourcePrice());
			orderDetail.setPrice(course.getPrice());
			orderDetail.setCourseId(course.getCourseId());
			orderDetail.setCourseName(course.getCourseName());
			orderDetail.setAuthStatus(OrderStatus.INIT.toString());
			orderDetail.setOrderNo(order.getOrderNo());
			orderDetail.setUpdateTime(curTime);
			orderDetail.setDescription(course.getCourseName());
			orderDetail.setOrderType(OrderType.COURSE.toString());
			orderDetailService.insert(orderDetail);
		}
		return createPayRequest(request, order);
	}

	/**
	 * 购买课程订单
	 *
	 * @param request
	 * @return
	 */
	public AjaxResult createCourseOrders(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		int cartType = TKConvert.toInteger(request.getParameter("type"), 1);

		LocalDateTime curTime = LocalDateTime.now();
		// 原始金额
		int orderAmount = 0;
		String description = "购买课程";
		// 获得该用户购物车
		List<ShopCart> cartList = shopCartService.getListByUserId(user.getUserId(), cartType);
		if (ObjectUtils.isNull(cartList)) {
			return AjaxResult.error("购物车商品为空！");
		}
		// 循环该用户购物车中的课程全部的价格
		for (ShopCart shopcart : cartList) {
			CourseDTO course = courseService.getDTO(shopcart.getGoodsId());
			if (ObjectUtils.isNull(course)) {
				shopCartService.deleteById(shopcart.getId(), user.getUserId());
				return AjaxResult.error("购物车中有已经过期的课程，已经删除，请刷新后重试！");
			}
			// 如果课程已经过期，将课程从购物车中删除，并重新加载购物车
			if (LocalDate.now().isAfter(course.getExpireDate())) {
				shopCartService.deleteById(shopcart.getId(), user.getUserId());
				return AjaxResult.error("购物车中有已经过期的课程，已经删除，请刷新后重试！");
			}
			// 查询出的课程不为空则添加
			shopcart.setCourse(course);
			orderAmount += course.getPrice();
			description = course.getCourseName();
		}

		if (orderAmount <= 0) {
			return AjaxResult.error("需要支付的金额错误，请刷新页面后重试！");
		}
		int couponAmount = 0;
		//订单使用了优惠券
		long couponCodeId = TKConvert.toInteger(request.getParameter("couponCodeId"));
		CouponCodeDTO couponCodeDTO=null;
		//订单使用了优惠券，设置为使用状态
		if (couponCodeId > 0) {
			couponCodeDTO = couponCodeService.getDTO(couponCodeId);
			if (couponCodeDTO!=null && couponCodeDTO.getLimitAmount()>=orderAmount){
				couponAmount = couponCodeDTO.getAmount();
			}
			else{
				couponCodeId = 0L;
				couponCodeDTO = null;
			}
		}
		// 拼装订单数据
		Order order = new Order();
		order.setCreateTime(curTime);// 下单时间
		// 下单时间
		order.setCompanyId(company.getCompanyId()); //这里是平台机构Id，不是用户机构Id
		order.setUserId(user.getUserId());
		order.setUserName(user.getDisplayName());
		order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
		order.setStatus(OrderStatus.INIT.toString());// 交易装态
		order.setPayType(payType.toString());// 支付类型
		order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
		order.setReqIp(TKRequest.getIpAddr(request));
		order.setOrderType(OrderType.COURSE.toString());//商品类型
		order.setDescription(description);
		order.setOrderAmount(orderAmount); // 原始金额
		order.setCouponCodeId(couponCodeId);
		order.setCouponAmount(couponAmount);
		order.setPayAmount(orderAmount-couponAmount);//订单实际支付金额
		order.setCashAmount(order.getPayAmount());//在线支付金额
		order.setVmAmount(0);//虚拟账户扣除金额
		order.setBackAmount(0);//返现扣除金额
		// 添加订单
		int count = orderService.insert(order);
		if (count < 1) {
			return AjaxResult.error("创建订单失败！");
		}
		//更新优惠券使用状态
		if (couponCodeDTO != null) {
			couponService.updateUseNum(couponCodeDTO.getCouponId());//更新优惠券使用数
			if (couponCodeDTO.getUseType() == 2) {//非无限次使用权的优惠券编码才更新状态
				CouponCode couponCode = new CouponCode();
				couponCode.setPayTime(LocalDateTime.now());
				couponCode.setStatus(2);//已使用
				couponCode.setOrderId(order.getOrderId());//订单id
				couponCode.setOrderNo(order.getOrderNo());//订单请求号
				couponCode.setUserId(order.getUserId());//用户id
				couponCode.setUserName(order.getUserName());
				couponCode.setUseTime(LocalDateTime.now());//使用时间
				couponCode.setId(order.getCouponCodeId());
				couponCodeService.update(couponCode);//更新优惠券编码使用后的信息
			}
		}
		// 添加流水表
		List<OrderDetail> orderDetailList = new ArrayList<>();

		for (ShopCart shopcart : cartList) {
			Course course = shopcart.getCourse();
			if (ObjectUtils.isNull(course)) {
				continue;
			}
			// 创建流水
			OrderDetail orderDetail = new OrderDetail();
			// 用户id
			orderDetail.setUserId(user.getUserId());
			orderDetail.setUserName(user.getDisplayName());

			// 订单id
			orderDetail.setOrderId(order.getOrderId());

			// 时间段
			orderDetail.setAuthDate(course.getExpireDate());

			// 下单时间
			orderDetail.setCreateTime(curTime);
			// 课程原始价格
			orderDetail.setSourcePrice(course.getSourcePrice());
			// 课程实际支付价格
			orderDetail.setPrice(course.getPrice());
			// 课程id
			orderDetail.setCourseId(course.getCourseId());
			// 课程名
			orderDetail.setCourseName(course.getCourseName());
			// 课程状态
			orderDetail.setAuthStatus(OrderStatus.INIT.toString());
			// 订单请求号
			orderDetail.setOrderNo(order.getOrderNo());
			orderDetail.setUpdateTime(curTime);
			orderDetail.setDescription(course.getCourseName());
			/*流水为课程流水*/
			orderDetail.setOrderType(OrderType.COURSE.toString());
			orderDetailList.add(orderDetail);
		}
		// 批量添加流水
		orderDetailService.addBatchOrderDetail(orderDetailList);
		//完成后清空购物车
		shopCartService.deleteByUserId(order.getUserId(), cartType);
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	/**
	 * 购买会员订单
	 *
	 * @param request
	 * @return
	 */
	public AjaxResult createMemberOrder(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}

		int otherId = TKConvert.toInteger(request.getParameter("otherId"));

		LocalDateTime curTime = LocalDateTime.now();
		// 原始金额
		MemberSale memberSale = memberSaleService.get(otherId);
		if (memberSale == null) {
			return AjaxResult.error("查询会员价格错误！");
		}

		MemberType memberType = memberTypeService.get(memberSale.getTypeId());
		/*如果会员已停用*/
		if (ObjectUtils.isNotNull(memberType) && memberType.getStatus() != 0) {
			return AjaxResult.error("该类会员已停用");
		}

		/*订单金额为会员销售价格*/
		int orderAmount = memberSale.getPrice();

		// 拼装订单数据
		Order order = orderService.getRepeatOrder(user.getUserId(), otherId, OrderType.MEMBER.toString());
		if (order == null) {
			order = new Order();
			order.setCreateTime(curTime);// 下单时间
			order.setCompanyId(company.getCompanyId()); //这里是平台机构Id，不是用户机构Id
			order.setUserId(user.getUserId());
			order.setUserName(user.getDisplayName());
			order.setStatus(OrderStatus.INIT.toString());// 交易装态
			order.setPayType(payType.toString());// 支付类型
			order.setOrderType(OrderType.MEMBER.toString());//商品类型
			order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
			order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
			order.setReqIp(TKRequest.getIpAddr(request));
			order.setImgUrl(memberType.getImageUrl());
			order.setDescription("购买会员：" + memberSale.getName());
			order.setOrderAmount(orderAmount); // 原始金额
			order.setCouponAmount(0);
			order.setPayAmount(orderAmount);//订单实际支付金额
			order.setCashAmount(orderAmount);//在线支付金额
			order.setVmAmount(0);//虚拟账户扣除金额
			order.setBackAmount(0);//返现扣除金额
			// 添加订单
			int count = orderService.insert(order);
			if (count < 1) {
				return AjaxResult.error("创建订单失败！");
			}
			// 创建流水
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setCompanyId(order.getCompanyId());
			// 用户id
			orderDetail.setUserId(user.getUserId());
			orderDetail.setUserName(user.getDisplayName());
			// 订单id
			orderDetail.setOrderId(order.getOrderId());
			orderDetail.setOrderType(OrderType.MEMBER.toString());
			// 按所写时间推移过期时间
			orderDetail.setAuthDate(LocalDate.now().plusDays(memberSale.getDays()));
			// 下单时间
			orderDetail.setCreateTime(curTime);
			// 会员原始价格
			orderDetail.setSourcePrice(memberSale.getPrice());
			// 会员实际支付价格
			orderDetail.setPrice(memberSale.getPrice());
			// 相关id
			orderDetail.setCourseId(otherId);
			// 会员名
			orderDetail.setCourseName(memberSale.getName());
			// 订单状态
			orderDetail.setAuthStatus(OrderStatus.INIT.toString());
			// 订单请求号
			orderDetail.setOrderNo(order.getOrderNo());
			orderDetail.setUpdateTime(curTime);
			orderDetail.setDescription(memberSale.getName());
			//添加流水
			orderDetailService.insert(orderDetail);
		}
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	/**
	 * 生成充值订单
	 *
	 * @param request
	 * @return
	 */
	public AjaxResult createAccountOrder(HttpServletRequest request, User user) {
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		// 原始金额
		int orderAmount = TKConvert.toInteger(request.getParameter("amount"));
		if (orderAmount < 1) {
			//兼容otherId处理
			orderAmount = (TKConvert.toInteger(request.getParameter("otherId")))*100;
			if ((orderAmount /100) < 5) {
				return AjaxResult.error("充值金额不得小于5元！");
			}
		}
		if (orderAmount > 1000000) {
			return AjaxResult.error("充值金额不能大于1万元！");
		}
		LocalDateTime curTime = LocalDateTime.now();
		// 拼装订单数据
		Order order = new Order();
		// 下单时间
		order.setCreateTime(curTime);// 下单时间
		order.setUserId(user.getUserId());
		order.setUserName(user.getDisplayName());
		order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
		order.setStatus(OrderStatus.INIT.toString());// 交易装态
		order.setPayType(payType.toString());// 支付类型
		order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
		order.setReqIp(TKRequest.getIpAddr(request));
		order.setOrderType(OrderType.ACCOUNT.toString());//商品类型
		order.setDescription("账户充值" + (orderAmount ) + "元");
		order.setCompanyId(LoginUser.getCompanyId(request));
		order.setOrderAmount(orderAmount); // 原始金额
		order.setCouponAmount(0);
		order.setPayAmount(orderAmount);//订单实际支付金额
		order.setCashAmount(orderAmount);//在线支付金额
		order.setVmAmount(0);//虚拟账户扣除金额
		order.setBackAmount(0);//返现扣除金额
		// 添加订单
		int count = orderService.insert(order);
		if (count < 1) {
			return AjaxResult.error("创建订单失败！");
		}
		// 创建流水
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setCompanyId(order.getCompanyId());
		// 用户id
		orderDetail.setUserId(user.getUserId());
		orderDetail.setUserName(user.getDisplayName());
		// 订单id
		orderDetail.setOrderId(order.getOrderId());
		orderDetail.setOrderType(OrderType.ACCOUNT.toString());
		// 按所写时间推移过期时间
		orderDetail.setAuthDate(LocalDate.now());
		//下单时间
		orderDetail.setCreateTime(curTime);
		//原始价格
		orderDetail.setSourcePrice(order.getOrderAmount());
		//实际支付价格
		orderDetail.setPrice(order.getPayAmount());
		// 相关id
		orderDetail.setCourseId(0);
		orderDetail.setCourseName("账户充值" + (orderAmount / 100) + "元");
		// 订单状态
		orderDetail.setAuthStatus(OrderStatus.INIT.toString());
		// 订单请求号
		orderDetail.setOrderNo(order.getOrderNo());
		orderDetail.setUpdateTime(curTime);
		orderDetail.setDescription("账户充值" + (orderAmount / 100) + "元");
		// 批量添加流水
		orderDetailService.insert(orderDetail);
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	/**
	 * 购买书籍订单
	 *
	 * @param request
	 * @return
	 */
	public AjaxResult createBookOrder(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		//支付类型
		PayType payType = PayType.get(request.getParameter("payType"));
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		int otherId = TKConvert.toInteger(request.getParameter("otherId"));
		LocalDateTime curTime = LocalDateTime.now();
		//原始金额
		Book book = bookService.get(otherId);
		if (book == null) {
			return AjaxResult.error("查询书籍错误！");
		}
		//订单金额为会员销售价格
		int orderAmount = book.getPrice();
		//拼装订单数据
		Order order = new Order();
		order.setImgUrl(book.getCover());
		//这里是平台机构Id，不是用户机构Id
		order.setCompanyId(company.getCompanyId());
		order.setUserId(user.getUserId());
		order.setUserName(user.getDisplayName());
		order.setOrderNo(orderService.createOrderNo(user.getUserId()));//交易请求号
		order.setStatus(OrderStatus.INIT.toString());//交易装态
		order.setAddressId(TKConvert.toInteger(request.getParameter("addressId")));// 交易装态
		order.setPayType(payType.toString());//支付类型
		order.setReqChannel(ReqChannel.form(request).toString());//请求渠道
		order.setReqIp(TKRequest.getIpAddr(request));
		order.setDescription("购买书籍：" + book.getTitle());
		order.setOrderType(OrderType.BOOK.toString());//商品类型
		order.setOrderAmount(orderAmount);//原始金额
		order.setCouponAmount(0);
		order.setPayAmount(orderAmount);//实际支付金额
		order.setCashAmount(orderAmount);//在线支付金额
		order.setVmAmount(0);//虚拟账户扣除金额
		order.setBackAmount(0);//返现扣除金额
		order.setCreateTime(curTime);//下单时间
		//添加订单
		int count = orderService.insert(order);
		if (count < 1) {
			return AjaxResult.error("创建订单失败！");
		}
		//创建流水
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setCompanyId(order.getCompanyId());
		orderDetail.setUserId(user.getUserId());
		orderDetail.setUserName(user.getDisplayName());
		orderDetail.setOrderId(order.getOrderId());
		orderDetail.setOrderType(OrderType.BOOK.toString());
		orderDetail.setSourcePrice(book.getPrice());
		orderDetail.setPrice(book.getPrice());
		orderDetail.setCourseId(otherId);
		orderDetail.setCourseName(book.getTitle());
		orderDetail.setAuthDate(LocalDate.now().plusDays(365));
		orderDetail.setAuthStatus(OrderStatus.INIT.toString());
		orderDetail.setOrderNo(order.getOrderNo());
		orderDetail.setUpdateTime(curTime);
		orderDetail.setDescription(book.getTitle());
		orderDetail.setCreateTime(curTime);
		orderDetailService.insert(orderDetail);
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	public AjaxResult createPictureOrder(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		int otherId = TKConvert.toInteger(request.getParameter("otherId"));
		LocalDateTime curTime = LocalDateTime.now();
		Picture picture = pictureService.get(otherId);
		if (ObjectUtils.isNull(picture)) {
			return AjaxResult.error("找不到该素材！");
		}
		//原始金额
		int orderAmount = picture.getPrice();
		if (orderAmount <= 0) {
			return AjaxResult.error("需要支付的金额错误，请刷新页面后重试！");
		}
		// 拼装订单数据
		Order order = new Order();
		order.setImgUrl(picture.getCoverUrl());
		order.setCreateTime(curTime);// 下单时间
		// 下单时间
		order.setCompanyId(company.getCompanyId()); //这里是平台机构Id，不是用户机构Id
		order.setUserId(user.getUserId());
		order.setUserName(user.getDisplayName());
		order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
		order.setStatus(OrderStatus.INIT.toString());// 交易装态
		order.setPayType(payType.toString());// 支付类型
		order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
		order.setReqIp(TKRequest.getIpAddr(request));
		order.setOrderType(OrderType.PICTURE.toString());//商品类型
		order.setDescription("购买素材：" + picture.getTitle());
		order.setOrderAmount(orderAmount); // 原始金额
		order.setCouponAmount(0);
		order.setPayAmount(orderAmount);//订单实际支付金额
		order.setCashAmount(orderAmount);//在线支付金额
		order.setVmAmount(0);//虚拟账户扣除金额
		order.setBackAmount(0);//返现扣除金额
		// 添加订单
		int count = orderService.insert(order);
		if (count < 1) {
			return AjaxResult.error("创建订单失败！");
		}
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setUserId(user.getUserId());
		orderDetail.setUserName(user.getDisplayName());
		orderDetail.setOrderId(order.getOrderId());
		orderDetail.setAuthDate(LocalDate.now().plusDays(365));
		orderDetail.setCreateTime(curTime);
		orderDetail.setSourcePrice(picture.getPrice());
		orderDetail.setPrice(picture.getPrice());
		orderDetail.setCourseId(picture.getId());
		orderDetail.setCourseName(picture.getTitle());
		orderDetail.setAuthStatus(OrderStatus.INIT.toString());
		orderDetail.setOrderNo(order.getOrderNo());
		orderDetail.setUpdateTime(curTime);
		orderDetail.setDescription(picture.getTitle());
		orderDetail.setOrderType(OrderType.PICTURE.toString());
		orderDetailService.insert(orderDetail);
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	public AjaxResult createDocumentOrder(HttpServletRequest request, User user) {
		Company company = (Company) request.getAttribute("siteCompany");
		if (company == null) {
			return AjaxResult.error("获取网站信息错误！");
		}
		PayType payType = PayType.get(request.getParameter("payType"));// 支付类型
		if (payType == null) {
			return AjaxResult.error("订单支付方式错误！");
		}
		int otherId = TKConvert.toInteger(request.getParameter("otherId"));
		LocalDateTime curTime = LocalDateTime.now();
		Document document = documentService.get(otherId);
		if (ObjectUtils.isNull(document)) {
			return AjaxResult.error("找不到该资料！");
		}
		boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.DOCUMENT.ordinal(), otherId);
		if (isBuy) {
			return AjaxResult.error("您已经购买了此课程，不需要重复购买，请手动刷新页面后进入观看！");
		}
		if(document.getStatus() != 1){
			return AjaxResult.error("该资料已下架！");
		}
		//原始金额
		int orderAmount = document.getPrice();
		if (orderAmount <= 0) {
			return AjaxResult.error("需要支付的金额错误，请刷新页面后重试！");
		}
		// 拼装订单数据
		Order order = new Order();
		order.setImgUrl(document.getCover());
		order.setCreateTime(curTime);// 下单时间
		// 下单时间
		order.setCompanyId(company.getCompanyId()); //这里是平台机构Id，不是用户机构Id
		order.setUserId(user.getUserId());
		order.setUserName(user.getDisplayName());
		order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
		order.setStatus(OrderStatus.INIT.toString());// 交易装态
		order.setPayType(payType.toString());// 支付类型
		order.setReqChannel(ReqChannel.form(request).toString());// 请求渠道
		order.setReqIp(TKRequest.getIpAddr(request));
		order.setOrderType(OrderType.DOCUMENT.toString());//商品类型
		order.setDescription("购买资料：" + document.getTitle());
		order.setOrderAmount(orderAmount); // 原始金额
		order.setCouponAmount(0);
		order.setPayAmount(orderAmount);//订单实际支付金额
		order.setCashAmount(orderAmount);//在线支付金额
		order.setVmAmount(0);//虚拟账户扣除金额
		order.setBackAmount(0);//返现扣除金额
		// 添加订单
		int count = orderService.insert(order);
		if (count < 1) {
			return AjaxResult.error("创建订单失败！");
		}
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setUserId(user.getUserId());
		orderDetail.setUserName(user.getDisplayName());
		orderDetail.setOrderId(order.getOrderId());
		orderDetail.setAuthDate(LocalDate.now().plusDays(365));
		orderDetail.setCreateTime(curTime);
		orderDetail.setSourcePrice(document.getPrice());
		orderDetail.setPrice(document.getPrice());
		orderDetail.setCourseId(document.getId());
		orderDetail.setCourseName(document.getTitle());
		orderDetail.setAuthStatus(OrderStatus.INIT.toString());
		orderDetail.setOrderNo(order.getOrderNo());
		orderDetail.setUpdateTime(curTime);
		orderDetail.setDescription(document.getTitle());
		orderDetail.setOrderType(OrderType.DOCUMENT.toString());
		orderDetailService.insert(orderDetail);
		//直接返回支付请求数据，不要二次请求
		return createPayRequest(request, order);
	}

	/**
	 * 用户中心重新发起支付
	 */
	@RequestMapping("/repay.json")
	@ResponseBody
	public AjaxResult orderRepay(HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return AjaxResult.error("此功能需要登录后方或操作，请先登录！");
		}
		int orderId = TKConvert.toInteger(request.getParameter("orderId"));
		// 查询订单
		Order order = orderService.get(orderId);
		if (order == null || order.getUserId() != userId) {
			return AjaxResult.error("找不到指定订单！");
		}
		if (OrderStatus.SUCCESS.equals(order.getStatus())) {
			logger.info("订单已经支付成功，无需要重复支付！orderNo：" + order.getOrderNo());
			return complete(order);
		}
		if (order.getCreateTime().isBefore(LocalDateTime.now().plusMinutes(-30))) {
			return AjaxResult.error("订单支付已经超时，请取消后重新购买！");
		}
		// 余额不足，跳转到银行页面
		// 不够时，走银行流程，支付的金额为差的金额
		String payType = TKString.trim(request.getParameter("payType"));
		order.setPayType(payType);
		return createPayRequest(request, order);
	}

	private AjaxResult complete(Order order) {
		JSONObject data = new JSONObject();
		data.put("orderNo", order.getOrderNo());
		data.put("orderId", order.getOrderId());
		return AjaxResult.success("complete", data, 1);
	}

	/**
	 * 支付成功
	 */
	@RequestMapping("/pay/success.html")
	public String paySuccess(HttpServletRequest request, ModelMap model) {
		//订单号
		Order order;
		int orderId = TKConvert.toInteger(request.getParameter("orderId"));
		if (orderId > 0) {
			order = orderService.get(orderId);
		} else {
			order = orderService.getByOrderNo(TKString.trim(request.getParameter("orderNo")));
		}
		if (order == null) {
			return toError404(request);
		}
		model.put("order", order);
		/*如果是课程订单*/
		if (OrderType.COURSE.equals(order.getOrderType())) {
			//订单里的 课程
			List<Course> courseList = courseService.getListByOrderNo(order.getOrderNo());
			model.put("courseList", courseList);
		} else if (OrderType.MEMBER.equals(order.getOrderType())) {
			OrderDetailQuery orderDetailQuery = new OrderDetailQuery();
			orderDetailQuery.setUserId(LoginUser.getUserId(request));
			orderDetailQuery.setOrderId(order.getOrderId());
			/*根据订单取流水*/
			List<OrderDetail> orderDetailList = orderDetailService.getList(orderDetailQuery);
			if (ObjectUtils.isNotNull(orderDetailList)) {
				/*根据流水取会员类型*/
				MemberSale memberSale = memberSaleService.get(orderDetailList.get(0).getCourseId());
				model.put("memberSale", memberSale);
			}
		}else if (OrderType.BOOK.equals(order.getOrderType())){
			orderExpressService.createExpress(order,userService.get(order.getUserId()));
		}
		return getViewPath("order/pay-success");
	}

	/**
	 * 订单验证是否支付成功
	 */
	@RequestMapping("/pay/check.json")
	@ResponseBody
	public AjaxResult checkOrderByOrderNo(HttpServletRequest request) {
		Order order;
		int orderId = TKConvert.toInteger(request.getParameter("orderId"));
		if (orderId > 0) {
			order = orderService.get(orderId);
		} else {
			order = orderService.getByOrderNo(TKString.trim(request.getParameter("orderNo")));
		}
		if (order == null) {
			return AjaxResult.error("未找到订单！");
		}
		if (OrderStatus.SUCCESS.equals(order.getStatus())) {// 订单支付成功
			return AjaxResult.success();
		} else {
			return AjaxResult.error();
		}
	}

	//生成支付请求
	private AjaxResult createPayRequest(HttpServletRequest request, Order order){
		//如果不是现金充值，查询否足够支付本次订单的，如果够，直接走扣账流程
		if ("ON".equals(CacheConstants.ACCOUNT_IS_OPEN) && !OrderType.ACCOUNT.equals(order.getOrderType())) {
			accountDeduct(request, order);
			if (order.getCashAmount() <= 0) {
				userLetterService.send(order.getUserId(), LetterTemplate.ORDER_SUCCESS, order.getOrderNo());
				return complete(order);
			}
		}
		if (PayType.ALIPAY.equals(order.getPayType())) {
			if ("ON".equals(CacheConstants.ALIPAY_IS_OPEN)) {
				return createAliPayRequest(request, order, websiteProfileService.getAlipay());
			} else {
				return AjaxResult.error("系统未启用【支付宝支付】功能，无法使用");
			}
		} else if (PayType.WXPAY.equals(order.getPayType())) {
			if ("ON".equals(CacheConstants.WXPAY_IS_OPEN)) {
				return createWxPayRequest(request, order, websiteProfileService.getWxpay());
			} else {
				return AjaxResult.error("系统未启用【微信支付】功能，无法使用");
			}
		} else {
			return AjaxResult.error("支付方式错误，请重新发起支付！");
		}
	}

	/**
	 * 生成支付宝请求地址
	 *
	 * @param request  HttpServletRequest
	 * @param order    订单
	 * @param alConfig 支付宝配置
	 * @return AjaxResult
	 */
	public AjaxResult createAliPayRequest(HttpServletRequest request, Order order, Map<String, Object> alConfig) {

		JSONObject data = new JSONObject();
		data.put("orderNo", order.getOrderNo());
		data.put("orderId", order.getOrderId());
		data.put("amount", order.getCashAmount());
		String payUrl = AliPay.gotoAlipay(order, alConfig);
		if (TKRequest.isMobileBrowse(request)) {
			data.put("payChannel", "H5");
		} else {
			data.put("payChannel", "PC");
		}
		data.put("payUrl", payUrl);
		return AjaxResult.success(data);
	}

	/**
	 * 生成微信支付请求地址
	 *
	 * @param request  HttpServletRequest
	 * @param order    订单
	 * @param wxConfig 微信支付配置
	 * @return AjaxResult
	 */
	public AjaxResult createWxPayRequest(HttpServletRequest request, Order order, Map<String, Object> wxConfig) {
		String payUrl;// = "/pay/order.html?orderNo=" + order.getOrderNo();
		//判断是否微信浏览器
		JSONObject data = new JSONObject();
		data.put("orderId", order.getOrderId());
		data.put("orderNo", order.getOrderNo());
		data.put("amount", order.getCashAmount());
		data.put("appId", wxConfig.get("appId"));
		data.put("timeStamp", WxPay.getTimeStamp());
		data.put("nonceStr", TKString.createUUID());
		try {
			if (TKRequest.isWxBrowse(request)) {
				UserThird userThird = userThirdService.getWx(order.getUserId());
				if (userThird == null) {
					return AjaxResult.error("获取微信openId错误，请重新登录后重试！");
				}
				//如果是手机端，直接返回H5支付连接即可
				payUrl = WxPay.JSAPI(order, userThird.getValueTwo(), wxConfig);
				data.put("package", "prepay_id=" + payUrl);
				//构造签名参数
				String message = String.format("%s\n%s\n%s\n%s\n"
						, data.get("appId")
						, data.get("timeStamp")
						, data.get("nonceStr")
						, data.get("package")
				);
				data.put("paySign", WxPay.getSign(message, (String) wxConfig.get("privateKey")));
				data.put("payChannel", "JSAPI");
			} else if (TKRequest.isMobileBrowse(request)) {
				//如果是手机端，直接返回H5支付连接即可
				payUrl = WxPay.h5(order, wxConfig);
				data.put("payChannel", "H5");
			} else {
				payUrl = WxPay.qrCode(order, wxConfig);
				//QRCodeUtils.decode(goUrl);
				data.put("payChannel", "PC");
			}
			data.put("payUrl", payUrl);
			return AjaxResult.success(data);
		} catch (Exception ex) {
			logger.error(ex.getMessage());
			return AjaxResult.error("微信支付错误，请与管理员联系！");
		}
	}

	public void accountDeduct(HttpServletRequest request, Order order) {
		//说明已经扣过虚拟账户的钱，避免重复扣除账户
		if (order.getVmAmount() > 0 || order.getBackAmount() > 0) {
			return;
		}
		int payAmount = order.getPayAmount();// 订单所需支付的金额(单位分)
		int deductAmount = order.getPayAmount(); //账户实扣款
		int useCashAmount = 0;//使用银行充值的金额(单位分)
		int useVmAmount = 0;//使用充值卡的金额(单位分)
		int useBackAmount = 0;//使用返现的金额(单位分)
		//获取用户账户信息
		UserAccount userAccount = userAccountService.getByUserId(order.getUserId());

		if (!AccountStatus.ACTIVE.toString().equals(userAccount.getAccountStatus())) {
			logger.info("账户被锁定，只能用在线支付。userId：" + order.getUserId());
			return;
		}
		if (userAccount.getBalance() < 1) {// 账户余额不足
			return;
		}
		if (userAccount.getVmAmount() >= payAmount) {// vm余额大于等于扣款的金额,vm足够支付
			useVmAmount = payAmount;//扣完
		} else if ((userAccount.getVmAmount() + userAccount.getBackAmount()) >= payAmount) {// vm余额+ back余额（返现余额） 大于等于扣款的金额,足够支付
			useVmAmount = userAccount.getVmAmount() > 0 ? userAccount.getVmAmount() : 0;//扣完
			useBackAmount = payAmount - useVmAmount;
		} else {// 不够的时候 再扣除cash的余额
			useVmAmount = userAccount.getVmAmount() > 0 ? userAccount.getVmAmount() : 0;//扣完
			useBackAmount = userAccount.getBackAmount() > 0 ? userAccount.getBackAmount() : 0;//扣完
			deductAmount = useVmAmount + useBackAmount;
			useCashAmount = payAmount - deductAmount;// 需要支付的金额
		}
		try {
			// 扣款，传入账户实扣款
			userAccountService.deduct(userAccount, deductAmount, AccountHistoryType.SALES, order.getOrderId(), order.getDescription(), true, AccountBizType.COURSE);
			order.setCashAmount(useCashAmount);
			order.setVmAmount(useVmAmount);
			order.setBackAmount(useBackAmount);
			//如果账户足够支付
			if (useCashAmount <= 0) {
				order.setPayType(PayType.ACCOUNT.toString());
				order.setStatus(OrderStatus.SUCCESS.toString());
				order.setPayTime(LocalDateTime.now());
				orderService.updateOrderStatusSuccess(order);
				if (!OrderType.MEMBER.equals(order.getOrderType())) {
					//分销消费返现
					userInviteService.orderCashback(request, order);
				}
			} else {
				orderService.updateOrder(order);
			}
		}catch (Exception ex){
			throw new RuntimeException(ex);
		}
	}
}